import {PageContainer} from "@ant-design/pro-layout";
import ProCard from "@ant-design/pro-card";
import type {ProTableProps} from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import type {SysDictTypeAdd, SysDictTypeData, SysDictTypeParams} from "@/pages/system/dict/type/type";
import columns from "@/pages/system/dict/type/list/config/columns";
import {Button, message, Space} from "antd";
import React, {useRef, useState} from "react";

import type {ActionType} from "@ant-design/pro-table/lib/typing";
import {
  downloadSysDictTypeExport,
  downloadSysDictTypeExportTemplate, sysDictTypeAdd,
  sysDictTypeImport,
  sysDictTypePageList,
  sysDictTypeRemove, sysDictTypeUpdate
} from "@/services/system/dict/type/api";
import type {OptionActions} from "@/type/type";
import Upload from "@/components/Upload";
import DictTypeAdd from "@/pages/system/dict/type/list/components/DictTypeAdd";
import type {ProFormInstance} from "@ant-design/pro-form";


export default () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<(number | string)[]>([]);

  const sysDictTypeAddRef: React.MutableRefObject<ProFormInstance<SysDictTypeAdd> | undefined> = useRef<ProFormInstance<SysDictTypeAdd> | undefined>();
  const optionAction: OptionActions<SysDictTypeAdd, SysDictTypeData> = {
    import: {
      maxCount: 1,
      showUploadList: false,
      beforeUpload: (file) => {
        const formData = new FormData();
        formData.append('file', file);
        sysDictTypeImport(formData).then((res) => {
          actionRef?.current?.reload();
        });
      }
    },
    edit(data) {
      sysDictTypeUpdate(data as SysDictTypeAdd).then(res => {
        message.success("操作成功").then()
        actionRef.current?.reload()
      })
    },
    editModal: (data: SysDictTypeData) => {
      return {
        trigger: <Button type="link" onClick={() => {
          sysDictTypeAddRef.current?.setFieldsValue(data)
        }}>编辑</Button>,
        onFinish: async (formData) => {
          await sysDictTypeAddRef.current?.validateFields().then(res => {
            const sysDictType: any = {
              ...formData,
              ...data
            }
            sysDictTypeUpdate(sysDictType).then(res => {
              message.success("操作成功")
              sysDictTypeAddRef.current?.resetFields();
              actionRef.current?.reload();
            })
          })
          return true
        },
        formRef: sysDictTypeAddRef,
        edit: true
      }
    },
    add() {
    },
    addModal: {
      trigger: <Button type="primary">新增</Button>,
      onFinish: async (formData) => {
        await sysDictTypeAddRef.current?.validateFields().then(res => {
          sysDictTypeAdd(formData as SysDictTypeAdd).then(res => {
            message.success("新增成功")
            sysDictTypeAddRef.current?.resetFields();
            actionRef.current?.reload();
          })
        })
        return true
      },
      formRef: sysDictTypeAddRef,
    },
    export() {
      downloadSysDictTypeExport(selectedRowKeys).then(res => {
        message.success("导出成功").then(res => {
          setSelectedRowKeys([]);
        })
      })
    },
    remove(ids) {
      sysDictTypeRemove([...ids, ...selectedRowKeys]).then(res => {
        message.success("删除成功").then(res => {
        })
        setSelectedRowKeys([]);
        actionRef.current?.reload();
      });
    }
    ,
    exportTemplate() {
      downloadSysDictTypeExportTemplate().then(res => {
        message.success("下载成功").then(res => {
        })
      })
    }
  }

// @ts-ignore
  const tableProps:
    ProTableProps<SysDictTypeData, SysDictTypeParams> = {
    rowSelection: {
      // selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
      // selections: [],
    },
    tableAlertRender: ({selectedRowKeys, selectedRows, onCleanSelected}) => {
      setSelectedRowKeys(selectedRowKeys);
      return (
        <Space size={24}>
                      <span>
                          已选 {selectedRowKeys.length} 项
                          <a style={{marginInlineStart: 8}} onClick={onCleanSelected}>
                           取消选择
                         </a>
                      </span>
        </Space>
      );
    },
    tableAlertOptionRender: () => {
      return (
        <Space size={16}>
          <a onClick={() => optionAction.remove([])}>批量删除</a>
          <a onClick={() => optionAction.export()}>导出数据</a>
        </Space>
      );
    },
    tableStyle: {},
    size: "small",
    bordered: true,
    columns: columns(optionAction),
    request: async (params, sort, filter) => {
      return await sysDictTypePageList(params).then(res => {
        return {
          data: res.data.records,
          success: true,
          total: res.data.total
        }
      })
    },
    headerTitle: (
      <Space>
        <DictTypeAdd edit={false} {...optionAction.addModal} layout="horizontal" title={"新增字典"} width={500}/>
        <Upload {...optionAction.import}>
          <Button type="primary">导入</Button>
        </Upload>
        <Button type="primary" onClick={() => optionAction.export()}>导出</Button>
        <Button type="primary" onClick={() => optionAction.exportTemplate()}>导出模版</Button>
      </Space>
    ),
    actionRef,
    rowKey: "id"
  }
  return (
    <PageContainer>
      <ProCard>
        <ProTable<SysDictTypeData, SysDictTypeParams> {...tableProps} />
      </ProCard>
    </PageContainer>
  )
}
